package com.cbgolf.oa.net;

import static android.util.Patterns.GOOD_IRI_CHAR;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import com.cbgolf.oa.app.App;
import com.cbgolf.oa.util.Util;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NetUtils {

  public static final int SUCCESS = 200;
  public static final int TOKEN_LOSE = 401;
  public static final int NO_PERMISSION = 403;
  public static final String BAIDU = "www.baidu.com";

  // 判断有网
  public static boolean isNetworkAvailable() {
    // Context context = activity.getApplicationContext();
    // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
    ConnectivityManager connectivityManager = (ConnectivityManager) App.getContext()
        .getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivityManager == null) {
      return false;
    } else {
      // 获取NetworkInfo对象
      NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
      if (networkInfo != null && networkInfo.length > 0) {
        for (int i = 0; i < networkInfo.length; i++) {
          // 判断当前网络状态是否为连接状态
          if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
            return true;
          }
        }
      }
    }
    return false;
  }

  /**
   * 检查网络是否可用
   */
  public static boolean checkEnable(Context paramContext) {
    boolean i = false;
    NetworkInfo localNetworkInfo = ((ConnectivityManager) paramContext
        .getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
    if ((localNetworkInfo != null) && (localNetworkInfo.isAvailable())) {
      return true;
    }
    return false;
  }

  /**
   * 将ip的整数形式转换成ip形式
   */
  public static String int2ip(int ipInt) {
    StringBuilder sb = new StringBuilder();
    sb.append(ipInt & 0xFF).append(".");
    sb.append((ipInt >> 8) & 0xFF).append(".");
    sb.append((ipInt >> 16) & 0xFF).append(".");
    sb.append((ipInt >> 24) & 0xFF);
    return sb.toString();
  }

  /**
   * 获取当前ip地址
   */
  public static String getLocalIpAddress(Context context) {
    try {
      WifiManager wifiManager = (WifiManager) context
          .getSystemService(Context.WIFI_SERVICE);
      WifiInfo wifiInfo = wifiManager.getConnectionInfo();
      int i = wifiInfo.getIpAddress();
      return int2ip(i);
    } catch (Exception ex) {
      return " 获取IP出错!!!!请保证是WIFI,或者请重新打开网络!\n" + ex.getMessage();
    }
    // return null;
  }

  public static boolean isFastMobileNetwork(Context context) {
    TelephonyManager telephonyManager = (TelephonyManager) context
        .getSystemService(Context.TELEPHONY_SERVICE);
    switch (telephonyManager.getNetworkType()) {
      case TelephonyManager.NETWORK_TYPE_1xRTT:
        return false; // ~ 50-100 kbps
      case TelephonyManager.NETWORK_TYPE_CDMA:
        return false; // ~ 14-64 kbps
      case TelephonyManager.NETWORK_TYPE_EDGE:
        return false; // ~ 50-100 kbps
      case TelephonyManager.NETWORK_TYPE_EVDO_0:
        return true; // ~ 400-1000 kbps
      case TelephonyManager.NETWORK_TYPE_EVDO_A:
        return true; // ~ 600-1400 kbps
      case TelephonyManager.NETWORK_TYPE_GPRS:
        return false; // ~ 100 kbps
      case TelephonyManager.NETWORK_TYPE_HSDPA:
        return true; // ~ 2-14 Mbps
      case TelephonyManager.NETWORK_TYPE_HSPA:
        return true; // ~ 700-1700 kbps
      case TelephonyManager.NETWORK_TYPE_HSUPA:
        return true; // ~ 1-23 Mbps
      case TelephonyManager.NETWORK_TYPE_UMTS:
        return true; // ~ 400-7000 kbps
      case TelephonyManager.NETWORK_TYPE_EHRPD:
        return true; // ~ 1-2 Mbps
      case TelephonyManager.NETWORK_TYPE_EVDO_B:
        return true; // ~ 5 Mbps
      case TelephonyManager.NETWORK_TYPE_HSPAP:
        return true; // ~ 10-20 Mbps
      case TelephonyManager.NETWORK_TYPE_IDEN:
        return false; // ~25 kbps
      case TelephonyManager.NETWORK_TYPE_LTE:
        return true; // ~ 10+ Mbps
      case TelephonyManager.NETWORK_TYPE_UNKNOWN:
        return false;
      default:
        return false;
    }
  }


  private String mScheme;
  private String mHost;
  private int mPort;
  private String mPath;
  private String mAuthInfo;

  static final int MATCH_GROUP_SCHEME = 1;
  static final int MATCH_GROUP_AUTHORITY = 2;
  static final int MATCH_GROUP_HOST = 3;
  static final int MATCH_GROUP_PORT = 4;
  static final int MATCH_GROUP_PATH = 5;

  /* ENRICO: imported the ParseExeption here */
  public static class ParseException extends RuntimeException {

    public String response;

    ParseException(String response) {
      this.response = response;
    }
  }

  //根据正则表达式进行判断
  static Pattern sAddressPattern = Pattern.compile(
            /* scheme    */ "(?:(http|https|file)\\:\\/\\/)?" +
            /* authority */ "(?:([-A-Za-z0-9$_.+!*'(),;?&=]+(?:\\:[-A-Za-z0-9$_.+!*'(),;?&=]+)?)@)?"
          +
            /* host      */ "([" + GOOD_IRI_CHAR + "%_-][" + GOOD_IRI_CHAR
          + "%_\\.-]*|\\[[0-9a-fA-F:\\.]+\\])?" +
            /* port      */ "(?:\\:([0-9]*))?" +
            /* path      */ "(\\/?[^#]*)?" +
            /* anchor    */ ".*", Pattern.CASE_INSENSITIVE);

  /**
   * parses given uriString.
   */
//用法:将需要判断的url传入,new WebAddress(address) 如果抛出异常,则会出现问题
  public NetUtils(String address) throws ParseException {
    if (address == null) {
      throw new NullPointerException();
    }

    // android.util.Log.d(LOGTAG, "WebAddress: " + address);

    mScheme = "";
    mHost = "";
    mPort = -1;
    mPath = "/";
    mAuthInfo = "";

    Matcher m = sAddressPattern.matcher(address);
    String t;
    if (m.matches()) {
      t = m.group(MATCH_GROUP_SCHEME);
      if (t != null) {
        mScheme = t.toLowerCase(Locale.getDefault());
      }
      t = m.group(MATCH_GROUP_AUTHORITY);
      if (t != null) {
        mAuthInfo = t;
      }
      t = m.group(MATCH_GROUP_HOST);
      if (t != null) {
        mHost = t;
      }
      t = m.group(MATCH_GROUP_PORT);
      if (t != null && t.length() > 0) {
        // The ':' character is not returned by the regex.
        try {
          mPort = Integer.parseInt(t);
        } catch (NumberFormatException ex) {
          throw new ParseException("Bad port");
        }
      }
      t = m.group(MATCH_GROUP_PATH);
      if (t != null && t.length() > 0) {
                /* handle busted myspace frontpage redirect with
                   missing initial "/" */
        if (t.charAt(0) == '/') {
          mPath = t;
        } else {
          mPath = "/" + t;
        }
      }

    } else {
      // nothing found... outa here
      throw new ParseException("Bad address");
    }

        /* Get port from scheme or scheme from port, if necessary and
           possible */
    if (mPort == 443 && mScheme.equals("")) {
      mScheme = "https";
    } else if (mPort == -1) {
      if (mScheme.equals("https")) {
        mPort = 443;
      } else {
        mPort = 80; // default
      }
    }
    if (mScheme.equals("")) {
      mScheme = "http";
    }
  }

  @Override
  public String toString() {
    String port = "";
    if ((mPort != 443 && mScheme.equals("https")) ||
        (mPort != 80 && mScheme.equals("http"))) {
      port = ":" + Integer.toString(mPort);
    }
    String authInfo = "";
    if (mAuthInfo.length() > 0) {
      authInfo = mAuthInfo + "@";
    }

    return mScheme + "://" + authInfo + mHost + port + mPath;
  }

  public void setScheme(String scheme) {
    mScheme = scheme;
  }

  public String getScheme() {
    return mScheme;
  }

  public void setHost(String host) {
    mHost = host;
  }

  public String getHost() {
    return mHost;
  }

  public void setPort(int port) {
    mPort = port;
  }

  public int getPort() {
    return mPort;
  }

  public void setPath(String path) {
    mPath = path;
  }

  public String getPath() {
    return mPath;
  }

  public void setAuthInfo(String authInfo) {
    mAuthInfo = authInfo;
  }

  public String getAuthInfo() {
    return mAuthInfo;
  }

  public static boolean isTest() {
    return Util.isEquals(WebAPI.TEST_IP, WebAPI.IP);
  }

}